<!--
 * @Author: 宏联-vision java_hongwx@163.com
 * @Date: 2025-02-08 14:09:36
 * @LastEditors: liyin 2179253556@qq.com
 * @LastEditTime: 2025-07-29 14:04:15
 * @FilePath: \未来教育集团门户网站\src\components\Login.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-row class="login-main-box">
    <div class="img-box-view"><el-image :src="bgImg"></el-image></div>
    <!-- <div class="login-bg-box"></div> -->
    <div class="school-logo-view">
      <el-image :src="schoolLogo"></el-image>
    </div>
    <el-row class="demo-ruleForm">
      <el-row class="user-logo-box">
        <el-image :src="userLogo"></el-image>
      </el-row>
      <el-row class="login-admin-box">欢迎登录</el-row>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" style="width: 100%" label-width="auto"
        size="default" status-icon>
        <el-form-item label="" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入账号">
            <template #prefix>
              <el-image :src="user"></el-image>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="" prop="pwd">
          <el-input v-model="ruleForm.pwd" type="password" show-password placeholder="请输入密码">
            <template #prefix>
              <el-image :src="pwd"></el-image>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="" prop="code">
          <el-row style="width: 100%">
            <el-col :span="12" style="padding-right: 0.47rem">
              <el-input v-model="ruleForm.code" placeholder="请输入验证码">
                <template #prefix>
                  <!-- <el-image :src="codeImg"></el-image> -->
                </template>
              </el-input>
            </el-col>
            <el-col :span="12" style="padding-left: 0.47rem">
              <div class="code-view-box" @click="getCode">
                <el-image :src="imgUrl" fit="cover"></el-image>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" type="primary" @click="submitForm(ruleFormRef)">
            {{ loading ? "正在登录" : "登 录" }}
          </el-button>
          <!-- <el-button @click="resetForm(ruleFormRef)">重置</el-button> -->
        </el-form-item>
      </el-form>
      <el-col :span="24" class="forget-pwd-box" @click="toEditPwd">忘记密码</el-col>
    </el-row>
    <div class="footer-bottom-box">
      <el-icon :size="14" class="iconfont icon-icon_copyright"></el-icon>
      <label>2025</label> 东莞市第一中学(集团)市十一中学 网版权所有
      <!-- <el-icon :size="14" style="margin-left: 10px;" class="iconfont icon-icon_support"></el-icon>
      技术支持：广东宏联科技有限公司 -->
    </div>
  </el-row>
</template>
<script lang="ts" setup>
import { onMounted, ref, reactive, onUnmounted } from "vue";
import { ElMessage, type ComponentSize, type FormInstance, FormRules } from "element-plus";
import Md5 from "js-md5";
import Base64 from "../util/Base64";
import { postLoginApi } from "../components/Api/login";
import { getLoginLeftMenuList } from "../components/Api/Operation";
import { useRoute, useRouter } from "vue-router";
import schoolLogo from "../assets/images/logo.png";
import userLogo from "../assets/images/logo2.png";
import user from "../assets/images/icon_zhanghao.png";
import pwd from "../assets/images/icon_mima.png";
// import codeImg from "../assets/images/emiyanzhengma.png";
import bgImg from "../assets/images/bg.png";
import { PiniaStore } from "../store";
import { useUserStore } from '../store/user'
import { useMeanStore } from '../store/menus'
interface RuleForm {
  name: string;
  pwd: string;
  code: string;
  rand_num: number;
}
const ruleForm = reactive<RuleForm>({
  name: "",
  pwd: "",
  code: "",
  rand_num: 0,
});
const isAdmin = ref<boolean>(false);
const store = PiniaStore();
const useSto = useUserStore()
const menusSto = useMeanStore()
const router = useRouter();
const route = useRoute();
const imgUrl = ref<string>("");
const loading = ref<boolean>(false);
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: "请输入账号", trigger: "blur" }],
  pwd: [
    {
      required: true,
      min: 5,
      max: 18,
      message: "请输入密码，最少5位数",
      trigger: "blur",
    },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
})
const formSize = ref<ComponentSize>("default");
const handelKeyup = (e?: any) => {
  if (e.keyCode === 13) {
    submitForm(ruleFormRef.value);
  }
}
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid: any) => {
    if (valid) {
      try {
        console.log("submit!");
        const base64 = new Base64();
        const result = base64.encode(ruleForm.name);
        const params = {
          login_name: result,
          login_passwd: Md5(ruleForm.pwd),
          rand_num: ruleForm.rand_num,
          code: ruleForm.code,
        };
        const res: any = await postLoginApi(params);
        if (res.code !== 1) {
          getCode()
          return ElMessage.error(res.message);
        }
        // window.localStorage.setItem("accessToken", res.data.accessToken);
        if (Number(res.data.is_first_login) === 1) {
          store.setOuterVisible(true);
        } else {
          store.setOuterVisible(false);
        }
        // store.setLoginForm(res.data);
        // 存储登陆者登录信息
        useSto.SET_INFO(res.data)
        // 存储token到缓存
        useSto.SET_TOKEN(res.data.accessToken)
        loading.value = false
        let i: number = 0
        if (JSON.parse(JSON.stringify(res.data)).menu.length > 0) {
          JSON.parse(JSON.stringify(res.data)).menu.forEach((item: any) => {
            if (item.children.length > 0) {
              i++
              if (i === 1) {
                router.replace(item.children[0].component)
              }
            }
          });
        }
        formEl.resetFields()
      } catch (error) {
        getCode();
        ElMessage.error("登录请求失败，请检查网络或稍后重试");
      }
    } else {
      console.log('error submit!')
    }
  })
}
// const resetForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   formEl.resetFields();
// };
const getCode = () => {
  var a = Math.round(Math.random() * 10000000);
  ruleForm.rand_num = a;
  // 判断当前环境是否为生产环境
  if (import.meta.env.MODE === "production") {
    // 生产环境逻辑
    imgUrl.value = "/admin/getValidateCode?rand_num=" + a;
  } else {
    // 开发环境逻辑
    imgUrl.value = "/api/admin/getValidateCode?rand_num=" + a;
  }
}

const toEditPwd = () => {
  router.push({ name: 'EditPwd', query: { type: 1 } })
}
onMounted(() => {
  getCode();
  console.log(route);
  window.addEventListener("keydown", handelKeyup);
  if (route.query.source === "admin") {
    isAdmin.value = true;
  } else {
    isAdmin.value = false;
  }
});
onUnmounted(() => {
  // 销毁事件
  window.removeEventListener("keydown", handelKeyup, false);
});
</script>
<style lang="scss" scoped>
.login-main-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  // background-image: url("../assets/images/loginbg.png");
  // background-size: 100% 100%;
  position: relative;

  .img-box-view {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

    .el-image {
      width: 100%;
      height: 100%;
      animation: zoomIn 20s infinite alternate;
    }
  }

  .login-bg-box {
    width: 100%;
    height: 100%;
    background-color: rgba($color: #000000, $alpha: 0.4);
    position: absolute;
    top: 0;
    left: 0;
  }

  .el-button {
    width: 100%;
    height: 48px;
  }

  .school-logo-view {
    position: absolute;
    left: 80px;
    top: 80px;
    width: 387px;
  }

  .login-admin-box {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 32px 0;
    padding-top: 70px;
    color: #333;
    // padding-top: 0;
    font-size: 28px;
    width: 100%;
    font-family: Bold;
  }
}

.demo-ruleForm {
  border: 1px solid #efefef;
  width: 400px;
  border-radius: 10px;
  padding: 30px;
  background: #FFFFFF;

  .el-image {
    width: 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
  }

  .user-logo-box {
    width: 128px;
    height: 128px;
    position: absolute;
    top: -64px;
    left: 50%;
    background-color: rgba($color: #fff, $alpha: 1);
    border-radius: 50%;
    transform: translate(-50%);
    display: flex;
    align-items: center;
    justify-content: center;

    .el-image {
      width: 100%;
      height: 100%;
      padding: 10px;
      margin-top: -10px;
      border: 2px solid #E4E4E4;
      border-radius: 50%;
    }
  }

  .code-view-box {
    // border: 1px solid #efefef;
    height: 48px;
    background-color: #efefef;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    .el-image {
      width: 100%;
      height: 100%;
      margin-top: 0px;
    }
  }
}

.footer-bottom-box {
  color: #666;
  display: flex;
  align-items: center;
  width: 100%;
  height: 40px;
  position: absolute;
  bottom: 0;
  justify-content: center;
  font-size: 13px;
  font-family: "Regular";

  label {
    margin-left: 10px;
  }
}

.forget-pwd-box {
  color: var(--el-color-primary);
  cursor: pointer;
  text-align: center;
}
@keyframes zoomIn {
  from {
    transform: scale(1);
  }

  to {
    transform: scale(1.3);
  }
}
</style>
<style lang="scss">
.login-main-box {
  .el-input__wrapper {
    padding: 10px;
  }
  .el-button {
    font-size: 1rem;
  }
}
</style>
